#include "cypher.h"

/*int
 main(int argc, char **argv)
 {
 cypherT cmsg1, cmsg2;
 int i;
 
 if( argc != 4 )
 {
 fprintf(stderr, "ERROR: 'Usage: %s MSG MSGLEN KEY'\n", argv[0]);
 return 1;
 }
 printf("\nMensaje Original:\t%s\t\tLongitud: %s\t\tKey: %s\n", argv[1], argv[2], argv[3]);
 
 printf("-----------------------------------------------------------------------------------------------------------------\n");
 
 cmsg1= cypher(argv[1], atoi(argv[2]), argv[3]);
 
 printf("Mensaje cifrado:\t");
 for(i= 0; i<cmsg1.len; i++)
 printf("%d ", cmsg1.msg[i]);
 printf("\t\tLongitud: %d\n", cmsg1.len);
 
 printf("-----------------------------------------------------------------------------------------------------------------\n");
 
 cmsg2= decypher(cmsg1.msg, cmsg1.len, argv[3]);
 
 printf("Mensaje descifrado:\t");
 for(i= 0; i<cmsg2.len; i++)
 printf("%c", cmsg2.msg[i]);
 printf("\t\tLongitud: %d\t\tKey: %s\n\n", cmsg2.len, argv[3]);
 
 free(cmsg1.msg);
 free(cmsg2.msg);
 return 0;
 }
 */

cypherT
cypher(void *msg, int len, char *key)
{
	cypherT cypher;
	int i, cqty, end= 0;
	unsigned char *auxkey, *auxmsg;
	
	cypher.msg= NULL;
	cypher.len= 0;
	if( len <= 0 || (auxkey= calloc(8, 1)) == NULL )
		return cypher;
	
	if( (cypher.msg= malloc(len+(8-len%8))) == NULL )
	{
		free(auxkey);
		return cypher;
	}
	if( (auxmsg= calloc(8, 1)) == NULL )
	{
		free(auxkey);
		free(cypher.msg);
		return cypher;
	}
	
	for(i= 0; i<8 && !end; i++)
	{
		auxkey[i]= key[i];
		if( key[i] == '\0' )
			end= 1;
	}
	cypher.len= len+(8-len%8);
	cqty= floor(len/8.0);
	
	for(i=0; i<cqty; i++)
		des_encipher(msg+(i*8), cypher.msg+(i*8), auxkey);
	
	strncpy((char *)auxmsg, msg+(i*8), len-(cqty*8));
	des_encipher(auxmsg, cypher.msg+(i*8), auxkey);
	
	free(auxmsg);
	free(auxkey);
	return cypher;
}

cypherT
decypher(void *msg, int len, char *key)
{
	cypherT cypher;
	int i, cqty, end= 0;
	unsigned char *auxkey;
	
	cypher.msg= NULL;
	cypher.len= 0;
	if( len <= 0 || (auxkey= calloc(8, 1)) == NULL )
		return cypher;
	
	if( (cypher.msg= malloc(len)) == NULL )
	{
		free(auxkey);
		return cypher;
	}
	
	for(i= 0; i<8 && !end; i++)
	{
		auxkey[i]= key[i];
		if( key[i] == '\0' )
			end= 1;
	}
	cypher.len= len;
	cqty= len/8;
	
	for(i=0; i<cqty; i++)
		des_decipher(msg+(i*8), cypher.msg+(i*8), auxkey);
	
	free(auxkey);
	return cypher;
}


int
cypher2(char * string, int len, char * key)
{
	cypherT cyphered;
	
	if(string == NULL)
		return -1;
	
	//printf("cyphstring:%s\n", string);
	cyphered = cypher(string, len, key);
	
	if(cyphered.msg == NULL)
		return -1;
	
	memcpy(string, cyphered.msg, cyphered.len);
	free(cyphered.msg);
	return 1;
}

int
decypher2(char * string, int len, char * key)
{
	cypherT decyphered;
	
	if(string == NULL)
		return -1;
	
	decyphered = decypher(string, len, key);
	
	if(decyphered.msg == NULL)
		return -1;
	
	memcpy(string, decyphered.msg, decyphered.len);
	//printf("desmsg:%s\n", decyphered.msg);
	
	free(decyphered.msg);
	return 1;
}
